﻿
/*
Description:
Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

*/

#include <sstream>
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
	int reverse(int x) {
		long long res = 0;
		while (x) {
			res = res * 10 + x % 10;
			x /= 10;
		}
		return (res<INT_MIN || res>INT_MAX) ? 0 : res;
		//return (int(res) == res) * res;
	}
	
	//int reverse2(int x, long r = 0) {
	//	return x ? reverse(x / 10, r * 10 + x % 10) : (int(r) == r) * r;
	//}

	int reverse_0(int x) {
		
		//cout << INT_MAX << " " << INT_MIN << endl;
		//cout << 0x7ffffffe << " " << 0xffffffff << endl;

		if (x > INT_MAX || x < INT_MIN)
		{
			return 0;
		}			

		int sign;
		sign = x >= 0 ? 1 : -1;
		long long num;
		num = abs(x);

		string str;
		str = std::to_string(num);
		//cout << str << endl;
		std::reverse(str.begin(), str.end());
		//cout << str<<endl;
		stringstream stream(str);
		stream >> num;

		/*
		char buf[20];
		memset(buf, 0, 20);

		//sprintf_s(buf, "%ld", num);
		itoa(num,buf,10);
		cout << buf << endl;

		char t;
		int len = strlen(buf);
		for (int i = 0; i < len / 2; i++)
		{
		t = buf[i];
		buf[i] = buf[len - i - 1];
		buf[len - i - 1] = t;
		}

		cout << buf << endl;

		//sscanf_s(buf, "%ld", &num);
		num=atoi(buf);
		*/
		if (int(num) != num)
		{
			return 0;
		}
		
		num *= sign;
		return num;
	}
	
};

int _ReverseInt()
{
	int num = 1534236469; // 120;// -123;// 123;//10;// 
	Solution solu;
	int result = 0;

	result = solu.reverse(num);

	cout << "num: " << num << endl;
	cout << "reverse: " << result << endl;
	return 0;
}